package algotithm.leetcode.stack.test227;

import java.util.ArrayDeque;
import java.util.Deque;

/**
 * @author zhouyanxiang
 * @Date 2021-01-2021/1/27-16:03
 * @Title 227. 基本计算器 II
 */
public class Solution {

    public static void main(String[] args) {
        Solution solution = new Solution();
        String s = "3-2*2 + 10";
        int calculate = solution.calculate(s);
        System.out.println(calculate);
    }

    public int calculate(String s) {
        Deque<Integer> deque = new ArrayDeque<>();
        char lastOp = '+';
        char[] ch = s.toCharArray();
        int len = ch.length;
        for (int i = 0; i < len; i++) {
            if (ch[i] == ' ') {
                continue;
            }
            if (Character.isDigit(ch[i])) {
                int tempNum = ch[i] - '0';
                while (++i < len && Character.isDigit(ch[i])) {
                    tempNum = tempNum * 10 + (ch[i] - '0');
                }
                i--;
                if (lastOp == '+') {
                    deque.push(tempNum);
                } else if (lastOp == '-') {
                    deque.push(-tempNum);
                } else {
                    deque.push(op(lastOp,deque.pop(),tempNum));
                }
            } else {
                lastOp = ch[i];
            }
        }

        int res = 0;
        for (int num : deque) {
            res += num;
        }
        return res;
    }

    public int op(char c,int a,int b) {
        if (c == '+') {
            return a + b;
        } else if (c == '-') {
            return a - b;
        } else if (c == '*') {
            return a * b;
        } else  {
            return a / b;
        }
    }

}
